package com.easychat.controller;

import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.List;
import java.util.Objects;

import com.easychat.annotation.GlobalInterceptor;
import com.easychat.entity.dto.TokenUserInfoDto;
import com.easychat.entity.enums.GroupStatusEnum;
import com.easychat.entity.enums.MessageTypeEnum;
import com.easychat.entity.enums.UserContactStatusEnum;
import com.easychat.entity.po.UserContact;
import com.easychat.entity.query.GroupInfoQuery;
import com.easychat.entity.po.GroupInfo;
import com.easychat.entity.query.UserContactQuery;
import com.easychat.entity.vo.GroupInfoVo;
import com.easychat.entity.vo.ResponseVO;
import com.easychat.exception.BusinessException;
import com.easychat.service.GroupInfoService;
import com.easychat.service.UserContactService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;

/**
 * 群组表 Controller
 */
@RestController("groupInfoController")
@RequestMapping("/group")
public class GroupInfoController extends ABaseController {

    @Resource
    private GroupInfoService groupInfoService;
    @Resource
    private UserContactService userContactService;

    /**
     * 创建 / 修改群组信息
     *
     * @param request     http请求
     * @param groupId     群组id
     * @param groupName   群组名称
     * @param joinType    加入类型
     * @param groupNotice 群组公告
     * @param avatarFile  头像文件
     * @param avatarCover 头像封面文件
     * @return
     */
    @PostMapping("/saveGroup")
    @GlobalInterceptor
    public ResponseVO saveGroup(HttpServletRequest request,
                                String groupId,
                                @NotEmpty String groupName,
                                @NotNull Integer joinType,
                                String groupNotice,
                                MultipartFile avatarFile,
                                MultipartFile avatarCover) throws IOException {
        // 从请求头中获取token对象
        TokenUserInfoDto tokenUserInfo = getTokenUserInfo(request);

        GroupInfo groupInfo = new GroupInfo();
        groupInfo.setGroupId(groupId);
        groupInfo.setGroupName(groupName);
        groupInfo.setJoinType(joinType);
        groupInfo.setGroupNotice(groupNotice);
        groupInfo.setGroupOwnerId(tokenUserInfo.getUserId());// 群主id
        groupInfo.setGroupOwnerNickName(tokenUserInfo.getNickName());// 群主昵称

        groupInfoService.savaGroup(groupInfo, avatarFile, avatarCover);


        return getSuccessResponseVO(null);

    }

    /**
     * 加载群组信息
     *
     * @param request 请求
     * @return 群组信息
     */
    @RequestMapping("/loadMyGroup")
    @GlobalInterceptor
    public ResponseVO loadMyGroup(HttpServletRequest request) {
        // 从请求头中获取token对象
        TokenUserInfoDto tokenUserInfo = getTokenUserInfo(request);

        GroupInfoQuery groupInfoQuery = new GroupInfoQuery();
        groupInfoQuery.setGroupOwnerId(tokenUserInfo.getUserId());
        groupInfoQuery.setOrderBy("create_time desc"); // 默认按创建时间倒序

        // 查询群组信息
        List<GroupInfo> groupList = groupInfoService.findListByParam(groupInfoQuery);
        return getSuccessResponseVO(groupList);

    }

    @RequestMapping("/getGroupInfo")
    public ResponseVO getGroupInfo(@NotEmpty String groupId,
                                   HttpServletRequest request) {
        GroupInfo groupInfo = getGroupInfoByGroupId(request, groupId);
        //从数据库查询群成员数量  并设置
        UserContactQuery userContactQuery = new UserContactQuery();
        userContactQuery.setContactId(groupId);
        Integer memberCount = userContactService.findCountByParam(userContactQuery);
        groupInfo.setMemberCount(memberCount);

        return getSuccessResponseVO(groupInfo);
    }

    /**
     * 获取聊天会话群聊信息
     *
     * @param groupId
     * @param request
     * @return
     */
    @RequestMapping("/getGroupInfo4Chat")
    @GlobalInterceptor
    public ResponseVO getGroupInfo4Chat(@NotEmpty String groupId,
                                        HttpServletRequest request) {
        GroupInfo groupInfo = getGroupInfoByGroupId(request, groupId);

        //设置查询群组中 群员 的条件
        UserContactQuery userContactQuery = new UserContactQuery();
        userContactQuery.setContactId(groupId);
        userContactQuery.setQueryUserInfo(true);
        userContactQuery.setOrderBy("create_time asc");
        userContactQuery.setStatus(UserContactStatusEnum.FRIEND.getCode());

        //查询群成员信息
        List<UserContact> userContactList = userContactService.findListByParam(userContactQuery);
        GroupInfoVo groupInfoVo = new GroupInfoVo();
        groupInfoVo.setGroupInfo(groupInfo);
        groupInfoVo.setUserContactList(userContactList);
        return getSuccessResponseVO(groupInfoVo);
    }

    /**
     * 根据群id 获取群组信息
     */
    private GroupInfo getGroupInfoByGroupId(HttpServletRequest request, String groupId) {


        //  校验发来请求的人的联系人中是否包含该群
        TokenUserInfoDto tokenUserInfo = getTokenUserInfo(request);
        String userId = tokenUserInfo.getUserId();
        //获取用户联系人  根据群id 和 用户id
        UserContact usercontact = userContactService.getUserContactByUserIdAndContactId(userId, groupId);
        if (usercontact == null || !UserContactStatusEnum.FRIEND.getCode().equals(usercontact.getStatus())) {
            throw new BusinessException("您不在群内或者您被踢出群，不能查看群组信息");
        }

//        System.out.println("groupID:" + groupId);
        GroupInfo groupInfo = groupInfoService.getGroupInfoByGroupId(groupId);
//        System.out.println("groupStatus:" + groupInfo.getStatus());
        if (!GroupStatusEnum.NORMAL.getCode().equals(groupInfo.getStatus())) {
            throw new BusinessException("群组不存在或已被封禁");
        }
        return groupInfo;
    }

    /**
     * 添加或者移除人员
     *
     * @param groupId        群id
     * @param selectContacts 选择的联系人的id集合
     * @param opType         操作类型 0:移除 1:增加
     * @return
     */
    @RequestMapping("/addOrRemoveGroupUser")
    @GlobalInterceptor
    public ResponseVO addOrRemoveGroupUser(@NotEmpty String groupId,
                                           @NotEmpty String selectContacts,
                                           @NotEmpty Integer opType,
                                           HttpServletRequest request) {
        TokenUserInfoDto tokenUserInfo = getTokenUserInfo(request);
        groupInfoService.addOrRemoveGroupUser(groupId, selectContacts, opType, tokenUserInfo);
        return getSuccessResponseVO(null);
    }

    @RequestMapping("/leaveGroup")
    @GlobalInterceptor
    public ResponseVO leaveGroup(@NotEmpty String groupId,
                                 HttpServletRequest request) {
        TokenUserInfoDto tokenUserInfo = getTokenUserInfo(request);
        groupInfoService.leaveGroup(tokenUserInfo.getUserId(), groupId, MessageTypeEnum.LEAVE_GROUP);
        return getSuccessResponseVO(null);
    }

    @RequestMapping("/dissolutionGroup")
    @GlobalInterceptor
    public ResponseVO dissolutionGroup(@NotEmpty String groupId, HttpServletRequest request) {
        TokenUserInfoDto tokenUserInfo = getTokenUserInfo(request);
        groupInfoService.dissolutionGroup(tokenUserInfo.getUserId(), groupId);

        return getSuccessResponseVO(null);
    }


}
